const financialService = require('../../../services/financial');
const calculator = require('../../../utils/calculator');

Page({
  data: {
    loading: true,
    stats: {
      currentYearProfit: 0,        // 本年收益
      currentYearRate: 0,          // 本年收益率
      lastYearRate: 0,             // 上年收益率
      totalPrincipal: 0,           // 锁定本金
      totalCount: 0,               // 持有笔数
      totalProfit: 0               // 总收益
    },
    // 持有本金分布
    principalDistribution: {
      fund: 0,        // 基金
      deposit: 0,     // 存款
      financial: 0    // 银行理财
    },
    // 本年度收益分布
    profitDistribution: {
      fund: 0,        // 基金
      deposit: 0,     // 存款
      financial: 0    // 银行理财
    },
    // 未来一年到期分布
    maturityDistribution: [],
    // 图表配置
    pieOpts: {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [{
        type: 'pie',
        radius: '50%',
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    },
    barOpts: {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: []
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        data: [],
        type: 'bar'
      }]
    }
  },

  onLoad() {
    this.loadData();
  },

  onPullDownRefresh() {
    this.loadData();
  },

  async loadData() {
    try {
      this.setData({ loading: true });
      const currentYear = new Date().getFullYear();
      
      // 获取所有产品列表
      const products = await financialService.getFinancialList();
      
      // 获取本年度收益统计
      const currentYearStats = await financialService.getYearlyProfit(currentYear);
      
      // 获取上年度收益统计
      const lastYearStats = await financialService.getYearlyProfit(currentYear - 1);

      // 计算统计数据
      const stats = this.calculateStats(products, currentYearStats, lastYearStats);
      
      // 计算分布数据
      const distributions = this.calculateDistributions(products, currentYearStats);
      
      // 计算到期分布
      const maturity = this.calculateMaturityDistribution(products);

      this.setData({
        stats,
        ...distributions,
        maturityDistribution: maturity,
        loading: false
      });

      // 更新图表数据
      this.updateCharts();
    } catch (error) {
      console.error('加载数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    } finally {
      wx.stopPullDownRefresh();
    }
  },

  // 计算统计数据
  calculateStats(products, currentYearStats, lastYearStats) {
    // 计算本年收益和收益率
    const currentYearProfit = currentYearStats.reduce((sum, item) => sum + item.profit, 0);
    const currentYearCost = currentYearStats.reduce((sum, item) => sum + item.cost, 0);
    const currentYearRate = currentYearCost > 0 ? (currentYearProfit / currentYearCost) * 100 : 0;

    // 计算上年收益率
    const lastYearProfit = lastYearStats.reduce((sum, item) => sum + item.profit, 0);
    const lastYearCost = lastYearStats.reduce((sum, item) => sum + item.cost, 0);
    const lastYearRate = lastYearCost > 0 ? (lastYearProfit / lastYearCost) * 100 : 0;

    // 计算总体统计
    const totalPrincipal = products.reduce((sum, item) => sum + item.money, 0);
    const totalProfit = products.reduce((sum, item) => sum + item.profit, 0);

    return {
      currentYearProfit,
      currentYearRate,
      lastYearRate,
      totalPrincipal,
      totalCount: products.length,
      totalProfit
    };
  },

  // 计算分布数据
  calculateDistributions(products, currentYearStats) {
    // 持有本金分布
    const principalDistribution = {
      fund: 0,
      deposit: 0,
      financial: 0
    };

    // 本年度收益分布
    const profitDistribution = {
      fund: 0,
      deposit: 0,
      financial: 0
    };

    // 计算本金分布
    products.forEach(item => {
      switch (item.type) {
        case '基金':
          principalDistribution.fund += item.money;
          break;
        case '定期存款':
        case '大额存单':
          principalDistribution.deposit += item.money;
          break;
        default:
          principalDistribution.financial += item.money;
      }
    });

    // 计算收益分布
    currentYearStats.forEach(item => {
      const product = products.find(p => p._id === item.financial_id);
      if (product) {
        switch (product.type) {
          case '基金':
            profitDistribution.fund += item.profit;
            break;
          case '定期存款':
          case '大额存单':
            profitDistribution.deposit += item.profit;
            break;
          default:
            profitDistribution.financial += item.profit;
        }
      }
    });

    return { principalDistribution, profitDistribution };
  },

  // 计算到期分布
  calculateMaturityDistribution(products) {
    const now = new Date();
    const oneYearLater = new Date();
    oneYearLater.setFullYear(now.getFullYear() + 1);

    // 按月分组到期金额
    const monthlyData = new Array(12).fill(0);
    
    products.forEach(item => {
      if (item.end_date) {
        const endDate = new Date(item.end_date);
        if (endDate >= now && endDate <= oneYearLater) {
          const monthIndex = endDate.getMonth();
          monthlyData[monthIndex] += item.money;
        }
      }
    });

    return monthlyData;
  },

  // 更新图表数据
  updateCharts() {
    const { principalDistribution, profitDistribution } = this.data;
    
    // 更新持有本金分布饼图
    const principalPieData = [
      { name: '基金', value: principalDistribution.fund },
      { name: '存款', value: principalDistribution.deposit },
      { name: '银行理财', value: principalDistribution.financial }
    ];

    // 更新本年度收益分布饼图
    const profitPieData = [
      { name: '基金', value: profitDistribution.fund },
      { name: '存款', value: profitDistribution.deposit },
      { name: '银行理财', value: profitDistribution.financial }
    ];

    // 更新到期分布柱状图
    const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
    
    this.setData({
      'pieOpts.series[0].data': principalPieData,
      'pieOpts2.series[0].data': profitPieData,
      'barOpts.xAxis.data': months,
      'barOpts.series[0].data': this.data.maturityDistribution
    });
  },

  // 跳转到新增页面
  navigateToAdd() {
    wx.navigateTo({
      url: '/pages/financial/add/add'
    });
  }
}); 